package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.MyConfig;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     * @param orders
     */
    @Transactional
    public Map<String, String> submit(Orders orders) {
//        A. 获得当前用户id, 查询当前用户的购物车数据
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);

        if(shoppingCarts == null || shoppingCarts.size() == 0){
            throw new CustomException("购物车为空，不能下单");
        }
//        B. 根据当前登录用户id, 查询用户数据
        User user = userService.getById(userId);
//        C. 根据地址ID, 查询地址数据
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if(addressBook==null){
            throw new CustomException("用户地址信息有误，不能下单");
        }
        long orderId = IdWorker.getId();//订单号
        AtomicInteger amount = new AtomicInteger(0);
//        D. 组装订单明细数据, 批量保存订单明细
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

//        E. 组装订单数据, 批量保存订单数据
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //向订单表插入数据，一条数据
        this.save(orders);
        //向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetails);
        //清空购物车数据
        shoppingCartService.remove(wrapper);
        Map<String, String> responseMap = null;
        try {
            responseMap = createOrderWx(orders.getId(), 1, orders.getUserName());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseMap;
    }
    private Map<String,String> createOrderWx(Long orderId, int price, String body) throws Exception {
        //1.创建wx配置赌侠昂
        MyConfig myConfig = new MyConfig();
        //2.创建wx支付核心对象
        WXPay wxPay = new WXPay(myConfig);
        //3.使用wxPay 来执行下单功能
        Map<String, String> requsetMap = new HashMap<>();
        //购买的商品信息
        requsetMap.put("body", "传智播客");
        //商家的订单号
        requsetMap.put("out_trade_no",orderId+"");
        //付款金额
        requsetMap.put("total_fee",price+"");//以分为单位

        requsetMap.put("spbill_create_ip","127.0.0.1");
        //回调通知  商家接收微信的信息的接口
        //公网的服务器接口
        requsetMap.put("notify_url","http://32633x11x9.zicp.vip/order/notifyAll");
        //支付类型
        requsetMap.put("trade_type","NATIVE");

        Map<String, String> responseMap = wxPay.unifiedOrder(requsetMap);

        responseMap.put("out_trade_no",orderId+"");

        return responseMap;
    }
    @Override
    public Page<Orders> findPage(Integer page, Integer pageSize, Long number, String beginTime,String endTime) {
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> wrapper=new LambdaQueryWrapper<>();
        if(number!=null){
            wrapper.eq(Orders::getId,number);
        }
        if(beginTime!=null&&endTime!=null){
            wrapper.between(Orders::getOrderTime,beginTime,endTime);
        }
        Page<Orders> ordersPage = this.page(pageInfo, wrapper);

            log.info("订单信息 {}"+ordersPage.getRecords());
        return ordersPage;
    }
    @Override
    public Page<Orders> findUserPage(Integer page, Integer pageSize) {
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        Page<Orders> ordersPage = this.page(pageInfo);
        return ordersPage;
    }

}